/*
 * @Author: Sa
 * @Date: 2018-10-06 22:32:02 
 * @Last Modified by: mikey.zhaopeng
 * @Last Modified time: 2018-10-07 20:28:03
 * @Description: 用户个人中心页面
 */
<template>
  <div>
    <!-- 1.头部 -->
    <my-header></my-header>

    <!-- 2.面板屑 -->
    <breadcrumb class="w user-breadcrumb">
      <span slot="message">个人中心</span>
    </breadcrumb>

    <!--3.个人中心信息 -->
    <div class="w user-info-card">
      <el-row :gutter="20">

        <!-- 3.1个人中心信息卡片 -->
        <el-col :span="18">
          <div class="grid-content bg-purple">
            <el-card class="box-card" shadow="hover">
              <div slot="header" class="clearfix">
                <el-tooltip class="item" effect="dark" :content="userInfo.username+'您已经注册'+userInfo.totalDays+'天了！'" placement="left">
                  <span style="font-size:20px">我的明信片 <i class="fa fa-vcard"></i></span>
                </el-tooltip>

                <el-button style="float: right; padding: 30px 0" type="text" @click="updteInfoShow=true">修改</el-button>
              </div>
              <div class="text item">
                <div class="user-img" v-if="userInfo.userImg">
                  <img v-lazy="userInfo.userImg" alt="">
                </div>
                <div v-else class="user-img">
                  <i class="fa fa-user-circle-o"></i>
                  <div>
                    <el-button type="text" @click="updatePwdShow=true">上传图片</el-button>
                  </div>

                </div>
                <div class="user-from">
                  <el-form status-icon label-width="150px" class="demo-ruleForm" label-position="left">
                    <el-form-item label="你猴吗->我就系>>" prop="pass">
                      <div class="form-item-value">
                        {{userInfo.username}}
                      </div>
                    </el-form-item>

                    <el-form-item label="绑定的手机号码>>" prop="pass">
                      <div v-if="userInfo.phone" class="form-item-value">
                        {{userInfo.phone}}
                      </div>
                      <div v-else class="form-item-unvalue">
                        暂未绑定手机号
                      </div>
                    </el-form-item>

                    <el-form-item label="绑定账号的邮箱>>" prop="pass">
                      <div v-if="userInfo.email" class="form-item-value">
                        {{userInfo.email}}
                      </div>
                      <div v-else class="form-item-unvalue">
                        暂未绑定邮箱
                      </div>
                    </el-form-item>

                    <el-form-item label="找回密码的问题>>" prop="pass">
                      <div v-if="userInfo.question" class="form-item-value">
                        {{userInfo.question}}
                      </div>
                      <div v-else class="form-item-unvalue">
                        暂未设置找回密码的问题
                      </div>
                    </el-form-item>

                    <el-form-item label="回答问题的答案>>" prop="pass">
                      <div v-if="userInfo.answer" class="form-item-value">
                        {{userInfo.answer}}
                      </div>
                      <div v-else class="form-item-unvalue">
                        问题都空着，答案肯定还没有咯！
                      </div>
                    </el-form-item>
                  </el-form>
                </div>
              </div>
            </el-card>
          </div>
        </el-col>

        <!-- 3.2侧边导航栏 -->
        <el-col :span="6">
          <!-- 3.2.1:导航栏菜单 -->
          <div class="grid-content bg-purple">
            <el-menu :default-openeds="['1']" class="el-menu-vertical-demo">
              <el-submenu index="1">
                <template slot="title">
                  <i class="el-icon-location"></i>
                  <!-- <span>个人中心</span> -->
                </template>
                <el-menu-item-group>
                  <el-menu-item index="1-1" @click="updteInfoShow=true"><i class="fa fa-address-card-o"></i> 更新信息</el-menu-item>
                  <el-menu-item index="1-2" @click="updatePwdShow=true"><i class="fa fa-lock"></i> 更新密码</el-menu-item>
                  <el-menu-item index="1-3" @click="updateImgShow=true"><i class="fa fa-user-o"></i> 更新头像</el-menu-item>
                  <el-menu-item index="1-4" @click="getImages(false)"><i class="fa fa-user-circle"></i> 我的头像</el-menu-item>
                </el-menu-item-group>
              </el-submenu>

            </el-menu>
          </div>

          <!-- 用户头像卡片 -->
          <el-collapse-transition>
            <el-card v-show="imagesCardShow" style="margin-top: 10px;">
              <div class="images-content">
                <div class="images" v-for="(image,index) in userInfo.imagesList" :key="index">
                  <img style="width=25%" v-lazy="image.url" :alt="image.createTime" @click="clickImage(image.url)">
                </div>
              </div>
              <div v-if="pagination.pageSize<pagination.total" class="image-pagination">
                <el-pagination :small=true layout="prev, next" :page-size="pagination.pageSize" :total="pagination.total" @prev-click="clickPre" @next-click="clickNext">
                </el-pagination>
              </div>
            </el-card>
          </el-collapse-transition>
        </el-col>
      </el-row>

    </div>

    <!-- 4.弹出的模态框 -->
    <!-- 4.1 用户更的模态框 -->
    <modal v-bind:mdShow="updteInfoShow" v-on:close="closeModal">
      <p slot="message">
        修改个人信息
      </p>
      <div slot="content">
        <el-form :rules="updateRules" ref="updateFrom" label-position="left" label-width="80px" :model="userInfo">

          <el-form-item label="用户名" prop="username">
            <el-input @blur="checkValue('username',userInfo.username)" v-model="userInfo.username" clearable placeholder="用户名长度为3~18个字符">
              <i slot="prefix" class="fa fa-user-o"></i>
            </el-input>
          </el-form-item>

          <el-form-item label="手机号" prop="phone">
            <el-input @blur="checkValue('phone',userInfo.phone)" v-model="userInfo.phone" clearable placeholder="请输入手机号">
              <i slot="prefix" class="fa fa-mobile-phone"></i>
            </el-input>
          </el-form-item>

          <el-form-item label="邮箱" prop="email">
            <el-input @blur="checkValue('email',userInfo.email)" type="email" v-model="userInfo.email" clearable placeholder="请输入邮箱">
              <i slot="prefix" class="fa fa-envelope-o fa-fw"></i>
            </el-input>
          </el-form-item>

          <el-form-item label="设置问题" prop="question">
            <el-input v-model="userInfo.question" clearable placeholder="通过该回答问题找回密码">
              <i slot="prefix" class="fa fa-question-circle-o"></i>
            </el-input>
          </el-form-item>

          <el-form-item label="我的答案" prop="answer">
            <el-input v-model="userInfo.answer" clearable placeholder="请回答 1988">
              <i slot="prefix" class="fa fa-unlock"></i>
            </el-input>
          </el-form-item>

          <el-form-item label="性别" prop="sex" class="radio-group">
            <el-radio-group v-model="userInfo.gender">
              <el-radio label='男' border>男</el-radio>
              <el-radio label='女' border>女</el-radio>
              <el-radio label='保密' border>保密</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item>
            <el-button style=" width:100%" type="primary" @click="update('updateFrom')">提交</el-button>
          </el-form-item>

        </el-form>
      </div>
    </modal>

    <!-- 4.2 更新密码的模态框 -->
    <modal v-bind:mdShow="updatePwdShow" v-on:close="closeModal">
      <p slot="message">
        修改密码
      </p>
      <div slot="content">
        <el-form :rules="updateRules" ref="updatePwdFrom" label-position="left" label-width="80px" :model="userInfo">

          <el-form-item label="原密码">
            <el-input type="password" v-model="userInfo.oldPwd" clearable placeholder="请输入原密码">
              <i slot="prefix" class="fa fa-user-o"></i>
            </el-input>
          </el-form-item>

          <el-form-item label="新密码" prop="newPwd">
            <el-input type="password" v-model="userInfo.newPwd" clearable placeholder="请输入新密码">
              <i slot="prefix" class="fa fa-mobile-phone"></i>
            </el-input>
          </el-form-item>

          <el-form-item label="新密码" prop="confrimPwd">
            <el-input type="password" v-model="userInfo.confrimPwd" clearable placeholder="请再次输入新密码">
              <i slot="prefix" class="fa fa-envelope-o fa-fw"></i>
            </el-input>
          </el-form-item>

          <el-form-item>
            <el-button style=" width:100%" type="primary" @click="updatePwd('updatePwdFrom')">提交</el-button>
          </el-form-item>

        </el-form>
      </div>
    </modal>

    <!-- 4.3 更新头像的模态框 -->
    <modal v-bind:mdShow="updateImgShow" v-on:close="closeModal">
      <p slot="message">
        更新头像
      </p>
      <div slot="content">
        <el-form label-position="left" label-width="80px" :model="userInfo">

          <el-form-item label="上传头像">
            <el-input type="file" ref="imagesFile"></el-input>
          </el-form-item>

          <el-form-item>
            <el-button style=" width:100%" type="primary" @click="uploadImages">提交</el-button>
          </el-form-item>

        </el-form>
      </div>
    </modal>

    <!-- 5 页脚 -->
    <my-footer class="user-footer"></my-footer>
  </div>
</template>

<script>
import Modal from "@/components/Modal";
import Breadcrumb from "@/components/Breadcrumb";
import MyHeader from "@/components/Header";
import MyFooter from "@/components/Footer";
import User from "@/service/user-service";
import UserImg from "@/service/user-img-service";
import Tips from "@/utils/tipsUtil";
import RulesUtil from "@/utils/rulesUtil";
const _user = new User();
const _userImg = new UserImg();
const _tips = new Tips();
const _regular = new RulesUtil();

export default {
  data() {
    //自定义的验证规则 用户名的校验规则
    let validateUsername = (rule, value, callback) => {
      let result = _regular.validate(value, "username");
      if (result) {
        callback(new Error(result));
      } else {
        callback();
      }
    };

    //自定义的验证规则 电话号码的验证
    let validatePhone = (rule, value, callback) => {
      let result = _regular.validate(value, "phone");
      if (result) {
        callback(new Error(result));
      } else {
        callback();
      }
    };

    //自定义的验证规则 邮箱的验证
    let validateEmail = (rule, value, callback) => {
      let result = _regular.validate(value, "email");
      if (result) {
        callback(new Error(result));
      } else {
        callback();
      }
    };
    //自定义的验证规则 问题的验证
    let validateQuestion = (rule, value, callback) => {
      if (_regular.validate(value, "require")) {
        callback();
      } else {
        callback(new Error("请输入你的问题"));
      }
    };

    //自定义的验证规则 答案的验证
    let validateAnswer = (rule, value, callback) => {
      if (_regular.validate(value, "require")) {
        callback();
      } else {
        callback(new Error("请输入回答问题答案"));
      }
    };

    //自定义的验证规则 密码的校验
    let validatePassWord = (rule, value, callback) => {
      if (_regular.validate(value, "require")) {
        length = value.length;
        if (length >= 3 && length <= 15) {
          callback();
        } else {
          callback(new Error("输入的密码的长度在3到15个字符"));
        }
      } else {
        callback(new Error("请输入密码！"));
      }
    };

    //自定义的验证规则 确认密码的校验
    let validateConfirmPwd = (rule, value, callback) => {
      if (_regular.validate(value, "require")) {
        length = value.length;
        if (length >= 3 && length <= 15) {
          if (this.userInfo.newPwd !== this.userInfo.confrimPwd) {
            callback(new Error("两次输入的密码不一致"));
          } else {
            callback();
          }
        } else {
          callback(new Error("输入的密码的长度在3到15个字符"));
        }
      } else {
        callback(new Error("请输入确认密码！"));
      }
    };

    return {
      //存储分页信息的对象
      pagination: {
        pageNum: 1, //当前的页数
        pageSize: 4, //页面大小
        total: 0 //总的条数（即总的用户头像个数）
      },

      //存储用户信息的对象
      userInfo: {
        userId: "", //用户id
        username: "姓名", //用户名
        phone: "手机号", //手机号
        email: "电子邮箱", //电子邮箱
        question: "问题", //问题
        answer: "答案", //答案
        gender: "性别", //性别
        userImg: "", //头像地址
        imageHost: "", //头像的主机地址（冗余字段）
        totalDays: 0, //成为系统用户总的天数

        oldPwd: "", //旧密码
        newPwd: "", //新密码
        confrimPwd: "", //确认密码

        imagesList: [] //头像列表
      },

      updteInfoShow: false, //更新信息的标志
      updatePwdShow: false, //更新密码的标志
      updateImgShow: false, //更新头像的标志
      imagesCardShow: false, //用户头像列表

      //更新的表单校验
      updateRules: {
        //用户名的校验
        username: [{ validator: validateUsername, trigger: "blur" }],
        //手机号的验证
        phone: [{ validator: validatePhone, trigger: "blur" }],
        //邮箱的验证
        email: [{ validator: validateEmail, trigger: "blur" }],
        //问题的验证
        question: [{ validator: validateQuestion, trigger: "blur" }],
        //答案的验证
        answer: [{ validator: validateAnswer, trigger: "blur" }],
        //密码的校验
        newPwd: [{ validator: validatePassWord, trigger: "blur" }],
        //确人密码的校验
        confrimPwd: [{ validator: validateConfirmPwd, trigger: "blur" }]
      }
    };
  },
  components: {
    Modal,
    Breadcrumb,
    MyFooter,
    MyHeader
  },
  mounted() {
    this.init();
  },
  methods: {
    /**
     *1.初始化，获取用户信息
     */
    init() {
      let vue = this;
      _user.getUserInfomation().then(
        res => {
          let result = res.data;
          vue.initUserInfoByResponse(result);
        },
        err => {
          _tips.notifyTips(vue, err.msg);
        }
      );
    },

    /**
     *2.关闭模态框
     */
    closeModal() {
      this.updteInfoShow = false;
      this.updatePwdShow = false;
      this.updateImgShow = false;
    },

    /**
     *3.更新用户信息
     */
    update(updateFrom) {
      let vue = this;
      vue.$refs[updateFrom].validate(valid => {
        let updateInfo = {
          username: vue.userInfo.username,
          email: vue.userInfo.email,
          phone: vue.userInfo.phone,
          question: vue.userInfo.question,
          answer: vue.userInfo.answer,
          gender: vue.userInfo.gender
        };
        _user.getUpdateInfromation(updateInfo).then(
          res => {
            _tips.notifyTips(vue, res.msg); //信息提示
            vue.updteInfoShow = false; //关闭模态框
            vue.initUserInfoByResponse(res.data); //缓存数据
          },
          err => {
            _tips.notifyTips(vue, err.msg);
          }
        );
      });
    },

    /**
     * 4.更新密码
     */
    updatePwd(updatePwdFrom) {
      let vue = this;
      vue.$refs[updatePwdFrom].validate(valid => {
        let pwdInfo = {
          passwordOld: vue.userInfo.newPwd,
          passwordNew: vue.userInfo.newPwd
        };
        _user.updatePwd(pwdInfo).then(
          res => {

            _tips.notifyTips(vue, res.msg);
            this.updatePwdShow = false;
            
            vue
              .$confirm("是否重新登录？", "修改密码成功", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "success"
              })
              .then(() => {
                vue.$router.push({path:'/login',name:'Login',query:{username: vue.userInfo.username}})
              })
              .catch(() => {
                this.$message({
                  type: "info",
                  message: "下次记得用新密码登录哦！"
                });
              });
          },
          err => {
            _tips.notifyTips(vue, err.msg);
          }
        );
      });
    },

    /**
     *5.上传用户头像
     */
    uploadImages() {
      let vue = this;
      const userId = vue.userInfo.userId;
      let file = this.$refs.imagesFile.$refs.input.files[0];
      _user.uploadImages(file, userId, res => {
        vue.updateImgShow = false; //关闭更新头像的模态框
        vue.userInfo.userImg = res.data.data[0].url; //缓存头像地址
        //插入用户头像记录
        _userImg.add(vue.userInfo.userImg).then(res=>{
          vue.getImages(); //刷新头像卡片 
        },err=>{
          _tips.notifyTips(vue, err.msg);
        })
        
      });
    },

    /**
     *6.获取我的的头像
     *@param paginationClick:布尔值：是否为分页的点击
     */
    getImages(paginationClick) {
      let vue = this;
      vue.imagesCardShow = !vue.imagesCardShow;

      //如果是分页点击触发该函数，需要显示头像卡片
      if (paginationClick) {
        vue.imagesCardShow = true;
      }
      if (vue.imagesCardShow) {
        let pageInfo = {
          pageNum: vue.pagination.pageNum,
          pageSize: vue.pagination.pageSize
        };
        _userImg.getImages(pageInfo).then(
          res => {
            vue.userInfo.imagesList = res.data.list;
            vue.pagination.total = res.data.total;
          },
          err => {
            _tips.notifyTips(vue, err.msg);
          }
        );
      }
    },

    /**
     *7.实时校验用户名、手机号。电子邮箱是否可用
     @param type:类型【取值为：用户名、手机号、邮箱】
     @param value:类型的值
     */
    checkValue(type, value) {
      let vue = this;
      _user.checkValid(type, value).then(
        res => {
          _tips.notifyTips(vue, res.msg);
        },
        err => {
          _tips.notifyTips(vue, err.msg);
        }
      );
    },

    /**
     * 8.点击分页组件前一页触发的事件
     */
    clickPre() {
      this.pagination.pageNum--;
      this.getImages(true);
    },
    /**
     * 9.点击分页组件的下一页的触发的事件
     */
    clickNext() {
      this.pagination.pageNum++;
      this.getImages(true);
    },

    /**
     *10.点击头像列表触发的更新头像的事件
     @param imageUrl:被点击头像的地址
     */
    clickImage(imageUrl) {
      _user.updateImage(imageUrl).then(
        res => {
          this.initUserInfoByResponse(res.data);
        },
        er => {
          _tips.notifyTips(vue, err.msg);
        }
      );
    },

    /**
     * ------------------------------------------------------------------------
     * 公共函数：缓存请求相应的数据
     */
    initUserInfoByResponse(result) {
      this.userInfo.userId = result.userId;
      this.userInfo.username = result.username;
      this.userInfo.phone = result.phone;
      this.userInfo.email = result.email;
      this.userInfo.question = result.question;
      this.userInfo.answer = result.answer;
      this.userInfo.gender = result.gender != null ? result.gender : "保密";
      this.userInfo.imageHost = result.imageHost;
      this.userInfo.userImg = result.userImg;
      this.userInfo.totalDays = result.totalDays;
    }
  }
};
</script>

<style scoped lang="scss">
//导航栏
.user-breadcrumb {

  margin: 0 auto;
}
//用户卡片
.user-info-card {

  margin: 0 auto;
  .clearfix {
    text-align: center;
  }
  .user-img {
    .fa-user-circle-o {
      font-size: 100px;
      padding: 0 0 10px 0;
      opacity: 0.5;
    }
  }
  .user-img img {
    height: 100px;
    width: 100px;
    border-radius: 50%;
    margin: 0 auto;
    padding: 0 0 10px 0;
    :hover {
      opacity: 0.8;
      cursor: pointer;
      background-color: red;
    }
  }
  .el-form-item__label {
    width: 120px;
    font-size: 11px;
  }
  .form-item-value {
    float: left;
  }
  .form-item-unvalue {
    float: left;
    color: #c60023;
    opacity: 0.7;
  }
}
// 性别按钮组的样式
.el-form-item.radio-group {
  text-align: left;
}
//头像列表
.images-content {
  position: relative;
  overflow: hidden;
  .images {
    float: left;
    width: 25%;
    height: auto;
    :hover {
      cursor: pointer;
      opacity: 0.7;
    }
    img {
      width: 100%;
      margin: 2px;
      border-radius: 50%;
    }
  }
}
//头像分页
.image-pagination {
  padding-top: 10px;
}
//页脚
.user-footer {
  position: absolute;
  bottom: 0px;
  width: 100%;
}
</style>
